package com.hpxx.ylzswl.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.hpxx.ylzswl.R;
import com.hpxx.ylzswl.base.BaseActivity;
import com.hpxx.ylzswl.event.NameEvent;
import com.hpxx.ylzswl.https.HttpAddress;
import com.hpxx.ylzswl.https.RequestParams;
import com.hpxx.ylzswl.utils.ConstantsUtils;
import com.universal.frame.generalutils.DateUtil;
import com.universal.frame.generalutils.GeneralUtil;
import com.universal.frame.generalutils.JsonUtil;
import com.universal.frame.generalutils.SharedPreferencesUtil;
import com.universal.frame.generalutils.ToastUtil;
import com.universal.frame.okhttp.OKHttpUtils;
import com.universal.frame.okhttp.ResultCallBack;
import com.universal.frame.pickerview.TimePickerView;

import java.io.IOException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.greenrobot.event.EventBus;
import okhttp3.Request;

import static com.activeandroid.Cache.getContext;

/**
 * Created by Administrator on 2017/11/9.
 */

public class MyProfileActivity extends BaseActivity implements
        RadioGroup.OnCheckedChangeListener ,View.OnClickListener,ResultCallBack{

    private RadioGroup mRadioGroup;
    private RadioButton bm,nan,nv;
    private TextView tv_my_time;
    private String userSex ;
    private TimePickerView pvTime; //时间选择器
    private EditText et_my_name;
    private TextView my_com_updata;
    private String name;
    private String birday;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_profile);
        back();
        setTitle("我的资料");
    }

    @Override
    public void initView() {
        my_com_updata = (TextView) findViewById(R.id.my_com_updata);
        et_my_name = (EditText) findViewById(R.id.et_my_name);
        et_my_name.setFilters(new InputFilter[]{emojiFilter, new InputFilter.LengthFilter(20)});
        mRadioGroup = (RadioGroup) findViewById(R.id.rg_my_selece_set);
        bm = (RadioButton) findViewById(R.id.rb_my_bm);
        nan = (RadioButton) findViewById(R.id.rb_my_nan);
        nv = (RadioButton) findViewById(R.id.rb_my_nv);
        tv_my_time = (TextView) findViewById(R.id.tv_my_time);
        mRadioGroup.setOnCheckedChangeListener(this);
        tv_my_time.setOnClickListener(this);
        my_com_updata.setOnClickListener(this);
        userSex = SharedPreferencesUtil.getString(this,ConstantsUtils.USER_SEX);
        if ("0".equals(userSex)){
            bm.setChecked(true);
            nan.setChecked(false);
            nv.setChecked(false);
        }else if ("1".equals(userSex)){
            bm.setChecked(false);
            nan.setChecked(true);
            nv.setChecked(false);
        }else {
            bm.setChecked(false);
            nan.setChecked(false);
            nv.setChecked(true);
        }
        name = SharedPreferencesUtil.getString(this,ConstantsUtils.USER_NAME);
        et_my_name.setText(name);
        initTime();

    }
    private void updatePersonalPost(String logisticRealname, String logisticBirthday,String logisticSex){
        OKHttpUtils.postAsync(this
                , HttpAddress.UPDATE_PERSONAL_URL
                , new RequestParams(this).getUpdatePersonalParams(logisticRealname,logisticBirthday,logisticSex), this
                ,true,1);
    }


    private void initTime(){
        pvTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        pvTime.setRange(1920,2100);//Calendar.getInstance().get(Calendar.YEAR) - 1
        pvTime.setTime(new Date());
        pvTime.setCyclic(true);
        pvTime.setCancelable(true);
        pvTime.setOnTimeSelectListener(new DateActionSheetListener(this));
        birday = SharedPreferencesUtil.getString(getApplicationContext(), ConstantsUtils.USER_BTD);
        tv_my_time.setText(birday);
        pvTime.setTime(DateUtil.formatStr2Date(birday.trim(), DateUtil.C_DATE_PATTON_DEFAULT));  //设置时间
    }

    @Override
    public void onSuccess(String response, int flag) {
        int status = JsonUtil.getInt(response, "status", 0);
        try {
            switch (flag) {
                case 1:
                    UpdateDetail(response);
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            GeneralUtil.tryShow(getContext(), e);
        }
    }

    private void UpdateDetail(String response) {
        int status = JsonUtil.getInt(response, "status", 0);
        String msg = JsonUtil.getString(response,"msg","");
        if (status == 1){
            //用户姓名
            SharedPreferencesUtil.putString(getApplicationContext(), ConstantsUtils.USER_NAME, name);
            //用户性别
            SharedPreferencesUtil.putString(getApplicationContext(), ConstantsUtils.USER_SEX, userSex);
            //用户生日
            SharedPreferencesUtil.putString(getApplicationContext(), ConstantsUtils.USER_BTD,birday);
            ToastUtil.showToast(getApplicationContext(),"修改成功！");
            EventBus.getDefault().post(new NameEvent(name));
        }else {
            ToastUtil.showToast(getContext(),msg);
        }
    }

    @Override
    public void onFailure(Request request, IOException e, int flag) {

    }

    private class DateActionSheetListener implements TimePickerView.OnTimeSelectListener {

        private Context context;

        public DateActionSheetListener(Context context) {
            super();
            this.context = context;
        }

        @Override
        public void onTimeSelect(Date date) {
            String strDate = DateUtil.formatDate2Str(date,
                    DateUtil.C_DATE_PATTON_DEFAULT);
            tv_my_time.setText(strDate);
        }
    }


    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.rb_my_bm:
                userSex = "0";
                break;
            case R.id.rb_my_nan:
                userSex = "1";
                break;
            case R.id.rb_my_nv:
                userSex = "2";
                break;

            default:
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_my_time:
                pvTime.show();
                break;
            case R.id.my_com_updata:
                 name = et_my_name.getText().toString().trim();
                 birday = tv_my_time.getText().toString().trim();
                if (name ==null&&name.isEmpty()){
                    ToastUtil.showToast(this,"真实姓名为空，请输入姓名");
                    return;
                }

                updatePersonalPost(name,birday,userSex);
                break;

            default:
                break;

        }
    }
    InputFilter emojiFilter = new InputFilter() {
        Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {

                return "";
            }
            return null;
        }
    };
}
